package controllers.manage.weixin;

import controllers.BaseController;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import models.constants.DeletedStatus;
import models.weixin.WeixinData;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信信息
 * Created by hanbin on 17/5/6.
 */
@With(BaseController.class)
public class WeixinDataCtrl extends Controller {

    /**
     * 跳转到微信管理页面
     */
    public static void index(Integer pageNumber, String name, String appId){
        pageNumber = pageNumber == null ? 1 : pageNumber;

        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(name)) {
            searchMap.put("name", "%"+name+"%");
        }
        if(StringUtil.isNotBlank(appId)) {
            searchMap.put("appId", appId);
        }

        flash.put("menuId", "1");

        JPAExtPaginator<WeixinData> resultPage = WeixinData.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber, name, appId);
    }

    /**
     * 跳转到新增微信页面
     */
    public static void add(){
        render();
    }

    /**
     * 跳转到修改微信页面
     */
    public static void modify(long id, Integer pageNumber){
        WeixinData weixinData = WeixinData.findById(id);
        render(weixinData, pageNumber);
    }


    /**
     * 创建微信信息
     */
    public static void create(WeixinData weixinData){
        weixinData.deleted = DeletedStatus.UN_DELETED;
        weixinData.save();
        flash.put("msg" , "微信信息创建成功");
        redirect("/BS0006/admin/weixin/index/1");
    }

    /**
     * 修改微信信息
     */
    public static void update(Long id, WeixinData weixinData, Integer pageNumber){
        WeixinData.update(id , weixinData);
        flash.put("msg" , "微信信息修改成功");
        redirect("/BS0006/admin/weixin/index/"+pageNumber);
    }

    /**
     * 删除微信信息
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        WeixinData weixinData = WeixinData.findById(id);
        //判断微信是否被使用,目前使用的是merchant,webUser
        if(WeixinData.checkIsUsed(id)){
            flash.put("msg" , "该微信号正在被使用,无法删除!");
            redirect("/BS0006/admin/weixin/index/"+pageNumber);
        }
        weixinData.deleted=DeletedStatus.DELETED;
        weixinData.save();
        flash.put("msg" , "微信信息删除成功");
        redirect("/BS0006/admin/weixin/index/"+pageNumber);
    }

}
